import {
  ElButton,
  ElCheckbox,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElNotification,
  FormInstance,
} from "element-plus";
import "../../login.less";
import { defineComponent, onMounted, reactive, ref } from "vue";
import IconMap from "@/config/sideNavIconMap";
import { loginApi } from "@/api/modules/login";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { useUserStore } from "@/stores/modules/user";
import { useRouter } from "vue-router";
import { useMenuStore } from "@/stores/modules/menu";
import { Login } from "@/api/interface";
import { useTheme } from "@/hooks/useTheme";
import { useGlobalStore } from "@/stores/modules/global";
import md5 from "md5";
export default defineComponent({
  name: "loginFrom",
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    const authStore = useMenuStore();
    const globalStore = useGlobalStore();
    const { changePrimary } = useTheme();
    const loginForm: Login.ReqLoginForm = reactive({
      username: "sq",
      password: "987654",
    });
    const loading = ref(false);
    // type FormInstance = InstanceType<typeof ElForm>;
    const loginFormRef = ref<FormInstance>();
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    const loginRules = reactive({
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    });

    const login = async () => {
      if (!loginFormRef.value) return;
      loginFormRef.value.validate(async (valid) => {
        if (!valid) return;
        loading.value = true;
        try {
          const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });

          userStore.setUserInfo(data);

          // 2.添加动态路由
          await initDynamicRouter();

          // 4.跳转到首页
          router.push(HOME_URL);
          ElNotification({
            title: getTimeState(),
            message: "欢迎登录",
            type: "success",
            duration: 3000,
          });
        } catch (error) {
          console.log("出错啦=>", error);
        } finally {
          loading.value = false;
        }
      });
    };

    onMounted(() => {
      changePrimary(globalStore.primary);
      // 监听 enter 事件（调用登录）
      document.onkeydown = (e: KeyboardEvent) => {
        e = (window.event as KeyboardEvent) || e;
        if (
          e.code === "Enter" ||
          e.code === "enter" ||
          e.code === "NumpadEnter"
        ) {
          if (loading.value) return;
          login();
        }
      };
    });

    return () => {
      return (
        <div>
          <ElForm
            ref={loginFormRef}
            size="large"
            model={loginForm}
            rules={loginRules}
          >
            <ElFormItem prop="username">
              <ElInput
                clearable
                v-model={loginForm.username}
                placeholder="请输入用户名"
                v-slots={{
                  prefix: () => (
                    <ElIcon class="el-input__icon">{IconMap["User"]}</ElIcon>
                  ),
                }}
              ></ElInput>
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput
                clearable
                v-model={loginForm.password}
                type="password"
                placeholder="请输入密码"
                show-password
                v-slots={{
                  prefix: () => (
                    <ElIcon class="el-input__icon">{IconMap["Lock"]}</ElIcon>
                  ),
                }}
              ></ElInput>
            </ElFormItem>
          </ElForm>
          <div class="login-btn">
            <ElButton
              round
              icon={IconMap["CircleClose"]}
              onClick={() => resetForm(loginFormRef.value)}
            >
              重置
            </ElButton>
            <ElButton
              round
              icon={IconMap["UserFilled"]}
              onClick={login}
              loading={loading.value}
              type="primary"
            >
              登录
            </ElButton>
          </div>
          {/* <div class="remenberPass">
            <ElCheckbox
              v-model={remenberP.value}
              style="margin-right: 5px"
              onChange={changeRemenber}
            ></ElCheckbox>
            <span>记住密码</span>
          </div> */}
        </div>
      );
    };
  },
});
